const fs = require("fs");
const path = require("path");
const { cwd } = require("process");
const test = /.json/;
const url = "/将json文件转换为excl文件/代转译的json文件";
let allData = {};
let outfile = "/将json文件转换为excl文件/data.json";
const xlsx = require("node-xlsx");
let stateData = []
let fileI = 0
init();

function init() {
  fs.stat(cwd() + url, (error, data) => {
    if (error) {
      console.error(error);
    } else {
      if (data.isDirectory()) {
        readdir(url);
      } else if (test.test(url)) {
        readFile(url,fileI++);
      }
    }
  });
}

function readFile(filepath,index) {
  const fileUrl = path.resolve(cwd() + filepath);
  stateData[index] = false
  fs.readFile(fileUrl, "utf-8", (error, data) => {
    if (error) {
      console.error(error);
    } else {
      stateData[index] = true
      allData = { ...allData, ...JSON.parse(data) };
      if(+stateData.indexOf(false)=== -1 ){
        execFile(allData);
      }
    }
  });
}

function readdir(dirpath) {
  const dirUrl = path.resolve(cwd() + dirpath);
  fs.readdir(dirUrl, "utf-8", (error, data) => {
    if (error) {
      console.error(error);
    } else {
      data.forEach((item) => {
        fs.stat(path.resolve(dirUrl + "/" + item), (error, data) => {
          if (error) {
            console.error(error);
          } else {
            if (data.isDirectory()) {
              readdir(dirpath + "/" + item);
            } else if (test.test(item)) {
              readFile(dirpath + "/" + item);
            }
          }
        });
      });
    }
  });
}

function writeFile(filepath, data) {
  console.log(path.resolve(cwd() + filepath));
  fs.writeFile(
    path.resolve(cwd() + filepath),
    data,
    { flag: "a+", encoding: "utf-8" },
    (err) => {
      console.error(err);
    }
  );
}

function execFile(data) {
  const tHeader = ["中文", "英文"];
  const list = [
    {
      name: "sheet",
      data: [tHeader],
    },
  ];
  for (let i in data) {
    list[0].data.push([i, data[i]]);
  }

  const buffer = xlsx.build(list);
  fs.writeFile("testFile.xlsx", buffer,{ flag: "a+", encoding: "utf-8" }, (err) => {
    if (err) {
      console.log(err, "保存excel出错");
    } else {
      console.log("写入excel成功!!!");
    }
  });
}
